package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.coyote.Request;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     *
     * @param dto 设备表
     * @return 结果
     */
    @Override
    public void updateDevice(DeviceDto dto) {
        // 1. 检查设备是否存在，如果不存在则抛出异常
        Device device = this.getById(dto.getId());
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //2. 判断设备名称是否重复，如果重复则抛出异常
        if (!device.getDeviceName().equals(dto.getDeviceName())) {
            long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
            if (count > 0) {
                throw new BaseException("设备名称重复");
            }
        }
        //3.检查设备标识(nodeId)是否重复，如果重复则抛出异常
        if (!device.getNodeId().equals(dto.getNodeId())) {
            long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
            if (count > 0) {
                throw new BaseException("设备标识重复");
            }
        }
        //4.封装数据并更改本地数据
        Device updatedDevice = BeanUtil.toBean(dto, Device.class);
        updatedDevice.setId(dto.getId());
        updatedDevice.setBindingLocation(String.valueOf(dto.getBindingLocation()));
        this.updateById(updatedDevice);
        //更新物联网平台的数据
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        AuthInfoWithoutSecret authInfo = new AuthInfoWithoutSecret();
        body.setAuthInfo(authInfo);
        request.setBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("更新设备信息失败");
        }
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     *
     * @param iotId 设备表主键
     * @return 结果
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        //删除本地数据
        boolean flag = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (!flag) {
            throw new BaseException("删除本地设备失败");
        }
        //删除物联网平台数据
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("删除平台设备失败");
        }
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest request = new ListProductsRequest();
        // 设置条数
        request.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步失败");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String productJsonStr = redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(productJsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(productJsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @return
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1.判断设备名称是否重复
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (ObjectUtil.isNotEmpty(device)) {
            throw new BaseException("设备名称重复");
        }
        //2.判断设备标识是否重复
        device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (ObjectUtil.isNotEmpty(device)) {
            throw new BaseException("设备标识重复");
        }
        //3.判断同一位置是否绑定了同一产品
        device = this.getOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
        if (ObjectUtil.isNotEmpty(device)) {
            throw new BaseException("同一位置只能绑定同一产品");
        }
        //4.注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        AuthInfo authinfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authinfo.setSecret(secret);
        body.setAuthInfo(authinfo);
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);
        //5.保存到本地数据库
        Device dev = BeanUtil.toBean(dto, Device.class);
        dev.setBindingLocation(String.valueOf(dto.getBindingLocation()));
        dev.setIotId(response.getDeviceId());
        dev.setSecret(secret);
        this.save(dev);
    }

    /**
     * 查询设备详细数据
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //通过iotId查询数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //查询物联网平台iot获取deviceStatus和activeTime
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备详情失败");
        }
        String status = response.getStatus();//获取设备状态
        String activeTimeStr = response.getActiveTime();//获取设备激活时间
        //封装数据
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        BeanUtil.copyProperties(device, deviceDetailVo);
        deviceDetailVo.setDeviceStatus(status);
        //转化时间格式
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = DateTimeZoneConverter.utcToShanghai(activeTime);
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据(影子数据）
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //1.查询物联网iot平台的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备上报数据失败");
        }
        //获取上报数据集合
        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollUtil.isEmpty(shadowList)) {
            return Collections.emptyList();
        }
        //获取上报数据的属性对象
        DeviceShadowProperties reported = shadowList.get(0).getReported();
        //获取json对象properties
        Object properties = reported.getProperties();
        JSONObject entries = JSONUtil.parseObj(properties);
        //获取上报数据的时间
        String eventTimeStr = reported.getEventTime();
        //转化时间格式
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyMMdd'T'HHmmss'Z'");
        //转换时区到上海
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        //2.封装数据并返回
        List<Map<String, Object>> list = new ArrayList<>();
        //遍历JSONObject类型的entries，封装成对应的属性值
        entries.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("产品标识不能为空");
        }
        //从平台获取产品属性数据
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (ObjectUtil.isEmpty(response)) {
            throw new BaseException("查询产品详情失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtils.isEmpty(serviceCapabilities)) {
            return Collections.emptyList();
        }
        return serviceCapabilities;
    }
}
